package com.nhncorp.pleiades.fs;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HadoopFileSystem extends PleiadesFileSystem {
  FileSystem fs;

  public HadoopFileSystem() throws IOException {
    Configuration conf = new Configuration();
    fs = FileSystem.get(conf);
  }

  
  public boolean exists(Path path) throws IOException {
    return fs.exists(new Path(path.toString()));
  }

  
  public boolean mkdirs(Path path) throws IOException {
    return fs.mkdirs(new Path(path.toString()));
  }

  
  public Path[] list(Path path) throws IOException {

    FileStatus[] fStatus = fs.listStatus(new Path(path.toString()));
    if (fStatus == null || fStatus.length == 0) {
      return null;
    }

    Path[] result = new Path[fStatus.length];
    for (int i = 0; i < fStatus.length; i++) {
      result[i] = fStatus[i].getPath();
    }
    return result;
  }

  
  public OutputStream create(Path path) throws IOException {
    return fs.create(new Path(path.toString()));
  }

  
  public InputStream open(Path path) throws IOException {
    return fs.open(new Path(path.toString()));
  }

  
  public void seek(InputStream in, long offset) throws IOException {
    ((FSDataInputStream) in).seek(offset);
  }

  
  public boolean delete(Path path) throws IOException {
    return fs.delete(new Path(path.toString()));
  }

  
  public void move(Path targetPath, Path destPath) throws IOException {
    mkdirs(destPath.getParent());
    fs.rename(new Path(targetPath.toString()), new Path(destPath.toString()));
  }

  
  public boolean isDirectory(Path path) throws IOException {
    return fs.isDirectory(new Path(path.toString()));
  }

  
  public long getLength(Path path) throws IOException {
    return fs.getLength(new Path(path.toString()));
  }

  
  public DataInputStream openDataInputStream(Path path) throws IOException {
    return fs.open(new Path(path.toString()));
  }

  public boolean renameTo(Path targetPath, Path destPath) throws IOException {
    return fs.rename(new Path(targetPath.toString()), new Path(destPath
        .toString()));
  }
}
